//
//  HuoQuShuJuTableViewController.m
//  10-10
//
//  Created by 钟纪旺 on 16/10/20.
//  Copyright © 2016年 zjw. All rights reserved.
//

#import "HuoQuShuJuTableViewController.h"
#import "WaitCell.h"
#import "ObtainData.h"

@interface HuoQuShuJuTableViewController ()
{
    NSMutableArray< ObtainItemData*> *data;
    int page;
    BOOL finished;
}

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *av;
@end

@implementation HuoQuShuJuTableViewController

- (void)viewDidLoad {
    UIRefreshControl *rc = [[UIRefreshControl alloc] init];
    rc.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
    [rc addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = rc;
    [super viewDidLoad];
    data = [NSMutableArray new];
    page = 1;
    finished = NO;
    self.navigationItem.rightBarButtonItem =self.editButtonItem;
    
}
- (void) refreshTableView
{
    if (self.refreshControl.refreshing) {// 判断是否处于刷新状态
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString: @"加载中..."];
        // 添加新的模拟器
        NSDate *date = [[NSDate alloc] init];
        // 模拟请求完成以后，回调方法callBackMethod
        [self performSelector:@selector(callBackMethod:) withObject:date afterDelay: 3];
    }
    
}
- (void) callBackMethod:(id) obj
{
    [self.refreshControl endRefreshing];	// 停止下拉刷新控件，回到初始状态
    self.refreshControl.attributedTitle =[[NSAttributedString alloc]initWithString:@"下拉刷新"];   // 文本变回来
    [self.Logs addObject:(NSDate *)obj];
    
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return data.count + 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < data.count) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mymy" forIndexPath:indexPath];
        ObtainItemData *item = data[indexPath.row];
        cell.textLabel.text = item.name;
        cell.detailTextLabel.text = item.tel;
        return cell;
    }else{
        WaitCell *cell = (WaitCell *)[tableView dequeueReusableCellWithIdentifier:@"mymymy" forIndexPath:indexPath];
        if (finished) {
            [cell.av stopAnimating];
            cell.tipsLabel.text = @"别拉了没了";
            return cell;
        }
        [cell.av startAnimating];
        cell.tipsLabel.text = @"";
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://xl18z.cn/list.php?page=%d",page++]];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data_, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 获取到数据了。
            NSString *text = [[NSString alloc] initWithBytes:data_.bytes length:data_.length encoding:NSUTF8StringEncoding];
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data_ options:NSJSONReadingAllowFragments error:nil];
          ObtainData *d = [[ObtainData alloc] initWithDictionary:dict];
            [data addObjectsFromArray:d.record];
            NSLog(@"%@",text);
            // GCD 大中枢派发
            dispatch_async(dispatch_get_main_queue(), ^{
                // 刷新界面代码
                if (d.record.count < 10) {
                    finished = YES;
                }
                [tableView reloadData];
            });
        }];
        [task resume];
        
        return cell;
    }
    
    
    
    return nil;
}
//-(nullable NSArray<UITableViewRowAction*>>)
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction *no1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        /*风格*/
    }];
    
    UITableViewRowAction *no2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"你来点一下" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }];
    no2.backgroundColor = [UIColor cyanColor];
    
       return @[no1,no2];
}
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{

    return YES;

}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{


}



@end

